package com.xnx3.util;

import java.io.IOException;

import com.xnx3.BaseVO;
import com.xnx3.Log;
import com.xnx3.SystemUtil;
import com.xnx3.UrlUtil;
import com.xnx3.net.HttpResponse;
import com.xnx3.net.HttpsUtil;
import com.xnx3.spider.cache.PageSpider;
import com.xnx3.spider.util.ChromeUtil;

import cn.zvo.http.Http;
import cn.zvo.http.Response;

/**
 * http、https请求
 * @author 管雷鸣
 */
public class HttpUtil {
	
	/**
	 * 获取网页源代码，自动根据url的协议获取
	 * @param url 绝对路径
	 * @return 若失败返回null，成功返回源代码
	 */
	public static BaseVO getContent(String url){
		BaseVO vo = new BaseVO();
		if(url == null){
			return BaseVO.failure("url is null");
		}
		
		//获取协议，是http，还是https
		String protocol = UrlUtil.getProtocols(url);
		if(protocol == null){
			protocol = "http";
		}
		//HttpResponse hr = null;
		Response res = null;
//		if(protocol.equalsIgnoreCase("https")){
//			Http http = new Http(PageSpider.encode);
//			res = http.get(url);
//		}else{
//			//只要不是https的，这里暂时都认为是http
//			com.xnx3.net.HttpUtil http = new com.xnx3.net.HttpUtil(PageSpider.encode);
//			hr = http.get(url);
//		}
		
		//暂时不启用这个
		if(SystemUtil.isWindowsOS() && true) {
			//windows ，则使用chrome
			ChromeUtil chrome = new ChromeUtil();
			vo = chrome.execute(url);
		}else {
			//其他，直接使用http的
			
			Http http = new Http(PageSpider.encode);
			try {
				res = http.get(url);
			} catch (IOException e) {
				e.printStackTrace();
				return BaseVO.failure(e.getMessage()+"\n url:"+url);
			}
			
			if(res == null){
				return BaseVO.failure("response is null");
			}
			if(res.getCode() != 200) {
				return BaseVO.failure("http response code:"+res.getCode()+", request url: "+url);
			}
			if(res.getContent() == null) {
				return BaseVO.failure("res.content is null");
			}
			
			vo.setInfo(res.getContent());
		}
		
		return vo;
	}
	
}
